package lormi.meipin.service.impl;

import lormi.meipin.common.LMOAuth2API;
import lormi.meipin.entity.Token;
import lormi.meipin.exception.LMException;
import lormi.meipin.service.BaseService;
import lormi.meipin.service.ITokenService;
import lormi.meipin.util.CacheUtil;
import lormi.meipin.util.DateUtil;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * token实现类
 * @author ThreeFeng
 * @date 2016年8月12日 下午5:46:13
 */
@Service
public class TokenService extends BaseService implements ITokenService{

	private Token getTokenByUserId(Integer id){
		Token t = (Token) CacheUtil.getCacheUtil().getLoginCache("token_"+id);
		if (t==null) {
			t = tokenMapper.selectByUserId(id);
			if (t==null) {
				throw new LMException(100031);
			}
			CacheUtil.getCacheUtil().setLoginCache("token_"+id, t);
		}
		return t;
	}

	@Override
	public void checkTokenValid(Integer id,String token) throws LMException{
		Token t =  getTokenByUserId(id);
		if (!token.equals(t.getToken())) {
			throw new LMException(100030);
		}
		//判断是否已经过期(15天有效期)
		if ((t.getExittime().getTime()-new Date().getTime())>=15*24*3600*1000.0) {
			t.setUpdatetime(new Date());
			t.setExittime(new Date(15*24*3600*1000+t.getUpdatetime().getTime()));
		}
	}

	@Override
	public Token insertToken(Integer userId) throws LMException {
		Token token = tokenMapper.selectByUserId(userId);
		if (token==null) {
			token = new Token();
			token.setUserid(userId);
			token.setToken(LMOAuth2API.getToken());
			token.setCreatetime(new Date());
			token.setUpdatetime(token.getCreatetime());
			token.setExittime(DateUtil.tokenExTime(token.getUpdatetime()));
			if (tokenMapper.insert(token)<1) {
				throw new LMException(100035);
			}
		} else {
			token.setUpdatetime(new Date());
			token.setExittime(DateUtil.tokenExTime(token.getUpdatetime()));
			if (tokenMapper.update(token)<1) {
				throw new LMException(100036);
			}
		}
		return token;
	}

	public static void main(String[] args) {
		System.out.println(15*24*3600*1000);
	}
	
}
